package com.leyou.mq;

import com.leyou.search.constans.MQConstants;
import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_UP_KEY;

@Component
public class ItemListener {
    @Autowired
    private SearchService searchService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SEARCH_ITEM_UP, durable = "ture"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_UP_KEY
    ))
    public void listenItemUp(Long spuId){
//判断是否为空
        if(spuId != null){
//            商品已经上架，需要写入索引库
            searchService.saveSpuById(spuId);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SEARCH_ITEM_DOWN, durable = "ture"),
            exchange = @Exchange(name = ITEM_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = ITEM_DOWN_KEY
    ))
    public void listenItemDown(Long spuId){
        if (spuId != null){
            searchService.deleteByid(spuId);
        }
    }
}
